import { createRouter, createWebHistory } from 'vue-router'
import DashboardView from '@/views/Dashboard/DashboardView.vue'
import LoginView from '@/views/Login/LoginView.vue'
import { ElMessage } from 'element-plus'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/dashboard/index'
    },
    {
      path: '/login',
      component: LoginView
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: DashboardView,
      // redirect:'/dashboard/index',
      children: [
        {
          path: 'index',
          name: 'index',
          component: () => import('@/views/Dashboard/IndexView.vue')
        },
        {
          path: 'user',
          name: 'user',
          component: () => import('@/views/User/UserView.vue')
        },
        {
          path: 'film',
          name: 'film',
          component: () => import('@/views/Film/FilmView.vue')
        },
        {
          path: 'cinema',
          name: 'cinema',
          component: () => import('@/views/Cinema/CinemaView.vue')
        }
      ]
    }
    // {
    //   path: '/about',
    //   name: 'about',
    //   // route level code-splitting
    //   // this generates a separate chunk (About.[hash].js) for this route
    //   // which is lazy-loaded when the route is visited.
    //   component: () => import('../views/AboutView.vue')
    // }
  ]
})
// 清空相关登录信息
const cleanAll = ()=>{
  localStorage.removeItem('expire')
  localStorage.removeItem('acl')
  localStorage.removeItem('jwt')
}
// 路由守卫 校验token
router.beforeEach((to, from, next) => {
  // console.log(to)
  // console.log(from)
  if (to.path === '/login') {
    next()
    return
  }
  if (localStorage.getItem('jwt')) {
    // 判断是否token是否过期
    let expire:number = Number(localStorage.getItem('expire'))
    let now = Math.ceil(new Date().getTime() / 1000)
    // console.log(expire);
    // console.log(now);
    if (now - expire > 7200) {
      ElMessage({
        showClose: true,
        message: '登录过期,请重新登录',
        type: 'error',
        duration: 1000,
        onClose: () => {
          next('/login')
        }
      })
      return
    }
    next()
  } else {
    ElMessage({
      showClose: true,
      message: '未登录,请登录',
      type: 'error',
      duration: 1000,
      onClose: () => {
        next('/login')
      }
    })
  }
})

export default router
